<?php
/****
 * filter
 * 功能描述 : 过滤检查类
 * 作	者  : qingkuangs(qingkuangs@gmail.com)
 * 日   期  : 2011-12-19
 *
****/
require_once(INCLUDE_PATH . "/common/uascii.class.php");
class filter {
	private static $charset = "UTF8";
	
	public static function check_filter($name, $minLen = 3, $maxLen = 20) {
		$nknamePattern  = "/[^\x{4e00}-\x{9fa5}A-Za-z0-9]+/u";
		$nkCharset = mb_detect_encoding($name, array('UTF-8', 'GB2312'));
		
		if($nkCharset != "UTF-8") {
			return -1;
		}
		if(strlen($name) < $minLen || strlen($name) > $maxLen) {
			return -2;
		}
		if(preg_match($nknamePattern,$name)) {
			return -3;
		}
		if(!self::check($name)) {
			return -4;
		}
		return 1;
	}
	
	public static function check($str) {
		if($str != "") {
			$filename = CONFIG_PATH . "/filter.data";
			

			$arrData = array();

			self::split_str($str,& $arrData);
			
			$strFilter = "/^(";
			for($i = 0,$len = count($arrData);$i < $len;$i++) {
				$strFilter .= ($i != 0) ? "|" : "";
				//$strFilter .= '$1 == "'.UAscii::encode($arrData[$i]).'"';

				$strFilter .= "".UAscii::encode($arrData[$i])." ";
			}
			$strFilter .= ")/";
			$shell = "awk '".$strFilter."' ".$filename;

			$content = shell_exec($shell);
			
			if($content == "")
				return true;
		}
		return false;
	}
	public static function deal($str) {
		if($str != "") {
			$filename = CONFIG_PATH . "/filter.data";

			$arrData = array();

			self::split_str($str,& $arrData);
			
			$strFilter = "/^(";
			for($i = 0,$len = count($arrData);$i < $len;$i++) {
				$strFilter .= ($i != 0) ? "|" : "";

				$strFilter .= "".UAscii::encode($arrData[$i])." ";
			}
			$strFilter .= ")/";
			$shell = "awk '".$strFilter."' ".$filename;

			$content = shell_exec($shell);
			
			if($content != "") {
				$arrData = explode("\n",$content);
				for($i = 0,$len = count($arrData);$i < $len;$i++) {
					if(!empty($arrData[$i])) {
						$strData = UAscii::decode(trim($arrData[$i]));
						
						if($strData != "") {
							$strRep = sprintf("%'*-".ceil(cstrlen($strData)/2)."s","");
							//$strRep = "**";

							$str = str_replace($strData,$strRep,$str);
						}
					}
				}
			}
		}
		return $str;
	}

	public static function split_str($str ,& $arrData) {
		$strlen = strlen($str);

		$strRemain = "";
		$iRemainStart = 0;
		$step = (self::$charset == "UTF8") ? 2 : 1;

		for($i = 0;$i < $strlen;$i++)  {
			$strTmp = "";
			$iRemainLen = 0;
			if(ord(substr($str,$i,1)) > 0xa0) {
				$strTmp = substr($str,0,($i + $step + 1));

				if($iRemainStart == 0) {
					$iRemainStart = $step + 1;
				}
				$i = $i + $step;
			} else {
				$strTmp = substr($str,0,($i + 1));

				if($iRemainStart == 0) {
					$iRemainStart = 1;
				}
			}

			if($i != 0)
				array_push($arrData,$strTmp);

			if($i > 6)
				break;
		}

		if($iRemainStart > 0) {
			self::split_str(substr($str,$iRemainStart),& $arrData);
		}
	}
}

?>